(function() {
	var util = require('common:widget/ui/libs/util.js').util,
        pageUtil =  {
		head : null,
        pid:1,
		current_page : 1,
		page_count : 0,
		current_tab : 'plat_tab',
		init : function() {
			var me = this,
                urlParam = util.getUrlParas();
            if(urlParam['pid']){
                me.pid = urlParam['pid'];
            }

			me.eventCenter();
			// me.loadCreditData();
            if(me.pid ==1){
                me.loadPlatTotalData();
                me.getProfitList();
                me.loadSummaryData();
            }
            me.loadPlatData();
		},
		loadCreditData : function() {
			var me = this;
			me.resetTable();
			$.getJSON('/plat/plat_credit_assemble' , {
                "current_page" : me.current_page,
                'pid':me.pid
            },function (data) {
				if(data && data.error_no == 0 && data.data) {
					me.page_count = data.data.page_count;
					var list = data.data.credit_assemble;
					var template = __inline("./credit.tmpl");
					var content = template({list:list});
    				$('.record_list').append(content);
					me.loadDataComplete();
				} else {
					if(data.error_no != 0) {
						alert(data.error_message);
					}
				}
			})
		},
		loadPlatData : function() {
			var me = this;
			me.resetTable();
			$.getJSON('/plat/plat_assemble' , {
                "current_page" : me.current_page,
                'pid':me.pid
            },function (data) {
				if(data && data.error_no == 0 && data.data) {
					me.page_count = data.data.page_count;
					var list = data.data.credit_plat;
					var template = __inline("./plat.tmpl");
					var content = template({list:list});
    				$('.record_list').append(content);
    				for (var i = 0; i < list.length; i++ ) {
    					me.renderPie($('.chart_icon').eq(i),list[i]);
    				};
					me.loadDataComplete();
				} else {
					if(data.error_no != 0) {
						alert(data.error_message);
					}
				}
			});
		},
		resetTable : function () {
			$('.record_list').empty();
		},
		loadPlatTotalData : function () {
            var me = this;
			$.getJSON('/plat/plat_total_buy',{
                'pid':me.pid
            },function(data) {
				if(data && data.error_no == 0 && data.data) {
					var snap_date = [];
					var plat_total_buy = [];
					for(var index in data.data) {
						snap_date.push(new Date(data.data[index].snap_date * 1000).pattern('MM-dd'));
						plat_total_buy.push(parseInt(data.data[index].plat_total_buy));
					}
					$('.credit_chart').highcharts({
				        chart: {
				            type: 'column'
				        },
				        title: {
				            text: '真融宝债权份额趋势图'
				        },
				        xAxis: {
				            categories: snap_date
				        },
				        credits: {
				            enabled: false
				        },
				        series: [{
				            name: '当日债权份额',
				            data: plat_total_buy,
				            color:'#ffeba3'
				        }]
				    });
				} else {
					if(data.error_no != 0) {
						alert(data.error_message);
					}
				}
			});
		},
		loadSummaryData : function() {
			var me = this;
			$.getJSON('/plat/plat_fund_summary' ,{
                'pid':me.pid
            },function (data) {
				if(data && data.error_no == 0 && data.data) {
					var usable_credit = parseInt(data.data.plat_credit_buy);
					$('.usable_amount_count').text("￥" + mathUtil.toCredit(usable_credit));
					$('#today_credit .ob_title').text("￥" + mathUtil.toCredit(data.data.plat_total_buy));
					$('#credit_count .ob_title').text(data.data.credit_assemble_total);
					$('#plat_count .ob_title').text(data.data.credit_plat_total);
					$('.profit_count span').text(mathUtil.formatAmount(data.user_total_profit,4));
                    if(usable_credit<=0){
                        $(".no_amount_tip").show();
                        $(".recharge-button").text('投资并排队');
                    }else{
                        $(".recharge-button").text('我要投资');
                    }
				} else {
					if(data.error_no != 0) {
						alert(data.error_message);
					}
				}
			})
		},
		loadDataComplete:function() {
			var me = this;
			if(!me.pagination) {
				var Pagination = require('home:widget/ui/pagination/pagination.js');
				me.pagination = new Pagination($('#record'), me.page_count);	
			} else {
				me.pagination.selectPage(me.current_page);
			}
		},
		eventCenter : function() {
			var me = this;
 			$('#record').bind('changePage',function(event,data) {
 				me.current_page = data.goto_num;
 				if(me.current_tab == 'plat_tab') {
 					me.loadPlatData();
 				} else {
 					me.loadCreditData();
 				}
 			});
 			$('.menu li').bind('click',function(event) {
 				if(event.preventDefault){
				    event.preventDefault();
				}else{
				    event.returnValue = false;
				}
 				if($(this).attr('id') != me.current_tab ) {
 					$('.menu li').removeClass('active');
 					$(this).addClass('active');
 					me.current_tab = $(this).attr('id');
 					me.current_page = 1;
 					me.pagination.dispose();
 					me.pagination = null;
 					if($(this).attr('id') == 'plat_tab' ) {
	 					me.loadPlatData();
	 				} else {
	 					me.loadCreditData();
	 				}

 				}
 			})
		},
		renderPie : function($selector, data) {
			$selector.highcharts({
				chart : {
					backgroundColor:'rgba(0,0,0,0)',
					borderColor:"#AAA"
				},
				credits : {
					enabled:false
				},
				title: {
					userHTML : true,
					text: ' ',
					color:'#FFF',
					align: 'center',
					verticalAlign: 'middle',
					y: -10
				},
				subtitle : {
					userHTML : true,
					text: ' ',
					verticalAlign:'middle',
					y:20
				},
				tooltip: {
					pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
				},
				legend: {
					borderColor: '#909090'
				},
				plotOptions: {
					pie: {
						borderWidth:"0px",
						size:"100%"
						// dataLabels: {
						// 	enabled: true
						// }
					}
				},

				series: [{
					type: 'pie',
					name: '占比',
					innerSize: '100%',
					data :[
						{
							name:'还款中',
							y:parseFloat(data.plat_status_2_percent),
							dataLabels : {
								enabled:false
							},
							color:'#6C3'
						},
						{
							name:'已还款',
							y:parseFloat(data.plat_status_3_percent),
							dataLabels : {
								enabled:false
							},
							color:'#669'
						},
						{
							name:'逾期',
							y:parseFloat(data.plat_status_456_percent),
							dataLabels : {
								enabled:false
							},
							color:'#F90'
						}
					]
				}]
			});
		},
        getProfitList : function() {
            var type="day",
                me = this;
            $.getJSON('/plat/plat_profit_trend',{
                'type':type,
                'pid':me.pid
            },function(data) {
                var date_list = [];
                var flab_list = [];
                var zrb_list = [];
                if(!data || data.error_no != 0) {
                    // alert(data.error_message);
                    $('#profit_compare').hide();
                    return;
                }
                for(var index in data.data.zrb_list) {
                    date_list.push(new Date(data.data.zrb_list[index].date * 1000).pattern('MM-dd'));
                    zrb_list.push(Math.floor(parseFloat(data.data.zrb_list[index].profit_percent) * 10000)/100);
                    if(data.data.flab_list) {
                        flab_list.push(parseFloat((parseFloat(data.data.flab_list[index].profit_percent)* 100).toFixed(2)));
                    }
                }
                $('#profit_compare').highcharts({
                    credits : {
                        enabled:false
                    },
                    title: {
                        text: '真融宝年化收益率趋势',
                        x: -20
                    },
                    xAxis: {
                        type:'datetime',
                        categories: date_list
                    },
                    yAxis: {
                        min:13,
                        title: {
                            text: '年化收益率(%)'
                        },
                        plotLines: [{
                            value: 0,
                            width: 1,
                            color: '#808080'
                        }]
                    },
                    tooltip: {
                        valueSuffix: '%'
                    },
                    plotOptions : {
                        area : {
                            fillOpacity:0.2
                        }
                    },
                    series: [{
                        type : 'area',
                        name: '真融宝',
                        data: zrb_list,
                        color:'#8a8ae6'
                    }]
                });
            });
        }
	};
	pageUtil.init();
})();


